﻿using System;
using System.Web.Mvc;
using ControleRepresentante.Logic.Models;
using ControleRepresentante.Logic.Repositories;
using WebSite.Controllers.ControllerExtensions;

namespace WebSite.Controllers
{
    public class MyInfoController : ControllerBase<IUserRepository>
    {
        public MyInfoController(IRepositoryProvider repositoryProvider, IControllerExtensionProvider controllerExtensionProvider) 
            : base(repositoryProvider, controllerExtensionProvider)
        {
        }

        public ActionResult Details()
        {
            User user = Repository.User;
            if (user == null)
            {
                throw new RestrictedAreaException();
            }
            return View("Details", user);
        }

        public ActionResult Edit()
        {
            User user = Repository.User;
            if (user == null)
            {
                throw new RestrictedAreaException();
            }
            return View(user);
        }

        [HttpPost]
        public ActionResult Edit(string password, string email)
        {
            User user = Repository.User;
            if (String.IsNullOrWhiteSpace(password))
            {
                user.ClearPassword();
            }
            else
            {
                user.SetPasswordFromRawText(password);
            }
            user.Email = email;
            ModelState.Clear();
            if (String.IsNullOrWhiteSpace(password) ||
                password.Trim() == String.Empty)
            {
                ModelState.AddModelError("Password", "*");
            }
            if (ModelState.IsValid)
            {
                Repository.UpdateModel(user, !user.IsAdmin);
                return Details();
            }
            return View(user);
        }
    }
}
